package offer;

import java.util.*;

public class offerII_0007 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list=new LinkedList<>();
        List<Integer> path=new LinkedList<>();
        int len=nums.length;
        Arrays.sort(nums);
        if(len<=2) return list;
        for(int i=0;i+2<len;++i){
            if(i>0&&nums[i]==nums[i-1]) continue;
            Set<Integer> set=new HashSet<>();
            int left=i+1;
            int right=len-1;
            while(left<right){
                if(nums[i]+nums[left]+nums[right]<0){
                    left++;
                }
                else if(nums[i]+nums[left]+nums[right]>0){
                    right--;
                }
                else {
                    if(!set.contains(nums[left])){
                        path.add(nums[i]);
                        path.add(nums[left]);
                        path.add(nums[right]);
                        set.add(nums[left]);
                        set.add(nums[right]);
                        list.add(new LinkedList(path));
                        path.clear();
                    }
                    left++;
                    right--;
                }
            }
        }
        return list;
    }

}
